package com.yonyou.cyxdms.basedata.client.util;

import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.MQBaseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * PO封装成存入MQ的数据对象
 *
 * @author ysj
 * @since 16:09 2019-10-22
 */
public class MqUtil<T> {
    private static final Logger log = LoggerFactory.getLogger(MqUtil.class);

    /**
     * 传入PO集合,返回根据OWNERCODE拆分的封装后的VO对象
     *
     * @author ysj
     * @date 2019/10/22
     * @param poList PO集合
     * @return
     */
    public List<MQBaseVO<List<T>>> listPoToListMap(List<T> poList){
        List<MQBaseVO<List<T>>> voList = new ArrayList<>();
        Map<String,List<T>> maps = new HashMap<>(10);

        poList.forEach(t -> {
            String appId = getValue(t,BaseDataCommonConstants.APP_ID);
            String ownerCode = getValue(t,BaseDataCommonConstants.OWNER_CODE);
            if(maps.get(appId+BaseDataCommonConstants.SPLIT_STR+ownerCode)==null){
                List<T> list = new ArrayList<>();
                list.add(t);
                maps.put(appId+BaseDataCommonConstants.SPLIT_STR+ownerCode,list);
            }else{
                maps.get(appId+BaseDataCommonConstants.SPLIT_STR+ownerCode).add(t);
            }
        });

        maps.keySet().forEach(key -> {
            String[] arr = key.split(BaseDataCommonConstants.SPLIT_STR);
            if(arr.length>0){
                MQBaseVO<List<T>> mqBaseVO = new MQBaseVO<>(maps.get(key),arr[0],arr[1]);
                voList.add(mqBaseVO);
            }
        });

        return voList;
    }

    /**
     * 反射获取appId和ownerCode设置到VO的最外层
     *
     * @author ysj
     * @date 2019/10/22
     * @param obj PO对象
     * @param fieldName 字段名
     * @return
     */
    public String getValue(Object obj,String fieldName){
        Field field = null;
        try {
            field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return String.valueOf(field.get(obj));
        } catch (NoSuchFieldException e) {
            log.error("反射获取字段失败：{}",e);
        } catch (IllegalAccessException e) {
            log.error("反射获取字段值失败：{}",e);
        }
        return "";
    }
}
